import articleMenus from './article/menu';
import websiteMenus from './website/menu';
import { IMenu } from './menu.interface';
import React, { Component } from 'react';
import userMenu from './user/menu';
import dashMenu from './dash/menu';

export class MenuManager { 
    menus: {[index: string]: any} = {
        'article': articleMenus,
        'website': websiteMenus,
        'user': userMenu,
        'dash': dashMenu,
    }
    sideMenus: IMenu;
    stateTarget: any;
    stateKey: string = 'menuMgr';
    component: Component;
    constructor(public mainMenuKey: string = 'article', public sideMenuKey: string = 'article-list') { 
        this.sideMenus = this.menus[this.mainMenuKey];
        this.component = this.getComponent();
    }
    init(stateTarget: any, key?: string) { 
        this.stateTarget = stateTarget;
        this.stateKey = key || this.stateKey;
    }
    goto(subMenuKey?: string, mainMenuKey?: string) {
        if (!mainMenuKey && !this.mainMenuKey) { 
            let key = this.getObjectFirstKey(this.menus);
            if (!key)
                return undefined;
            mainMenuKey = key;
        }
        this.mainMenuKey = mainMenuKey || this.mainMenuKey;
        this.sideMenus = this.menus[this.mainMenuKey];
        if (!subMenuKey) { 
            let key = this.getObjectFirstKey(this.sideMenus);
            if (!key)
                key = ""
            subMenuKey = key;
        }
        this.sideMenuKey = subMenuKey || this.sideMenuKey;
        this.component = this.getComponent();
        this.stateTarget && this.stateTarget.setState({[this.stateKey]: this.toJSON()})
    }
    gotoComponent(compoent: any) { 
        this.component = compoent;
        this.stateTarget && this.stateTarget.setState({ [this.stateKey]: this.toJSON() })
    }
    getComponent() { 
        let menu = this.menus[this.mainMenuKey || this.mainMenuKey][this.sideMenuKey];
        return menu && menu.component;
    }
    private getObjectFirstKey(obj: any) { 
        if (!obj)
            return undefined;
        let keys = Object.keys(obj);
        return keys && keys.length && keys[0] || undefined;
    }
    toJSON() { 
        return {
            sideMenuKey: this.sideMenuKey,
            menus: this.menus,
            sideMenus: this.sideMenus,
            mainMenuKey: this.mainMenuKey,
            component: this.component,
        }
    }
}
const menuMgr = new MenuManager();
export default menuMgr;
export { menuMgr };